package org.example.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BiMap<K, V> {
    private final Map<K, V> forward = new ConcurrentHashMap<>();
    private final Map<V, K> backward = new ConcurrentHashMap<>();

    public void put(K key, V value) {
        // 如果存在旧值，移除旧的反向映射
        if (forward.containsKey(key)) {
            V oldValue = forward.get(key);
            backward.remove(oldValue);
        }
        // 如果 value 已经存在其他 key，移除
        if (backward.containsKey(value)) {
            K oldKey = backward.get(value);
            forward.remove(oldKey);
        }
        forward.put(key, value);
        backward.put(value, key);
    }

    public V getValue(K key) {
        return forward.get(key);
    }

    public K getKey(V value) {
        return backward.get(value);
    }

    public boolean containsKey(K key) {
        return forward.containsKey(key);
    }

    public boolean containsValue(V value) {
        return backward.containsKey(value);
    }

    public void removeByKey(K key) {
        if (forward.containsKey(key)) {
            V value = forward.remove(key);
            backward.remove(value);
        }
    }

    public void removeByValue(V value) {
        if (backward.containsKey(value)) {
            K key = backward.remove(value);
            forward.remove(key);
        }
    }

    public int size() {
        return forward.size();
    }

    public void clear() {
        forward.clear();
        backward.clear();
    }
}
